<template>
    <div class="http-client-test">
        <background></background>
        <operation>
            <template slot="right">
                <el-tag v-if="activeOptionProject" class="option-tag" v-text="activeOptionProject"
                        type="success" size="mini"></el-tag>
                <el-input v-if="option.host" class="option-input" v-model="option.host"
                          size="mini" disabled></el-input>
                <el-button class="setting-btn" type="text" size="small"
                           icon="el-icon-setting" @click="settingClick"></el-button>
            </template>
        </operation>

        <!--console-->
        <div class="console">
            <el-select class="select" v-model="method" value="">
                <el-option v-for="method in Object.keys(requestMethods)"
                           :key="method" :label="method" :value="method">
                </el-option>
            </el-select>
            <el-input class="input" v-model="url">
                <template slot="suffix">
                    <i class="el-input__icon el-icon-more input-btn" @click="moreVisible = !moreVisible"></i>
                </template>
            </el-input>
            <el-button class="go-btn" v-loading="loading" @click="goClick">GO</el-button>
        </div>

        <!--more-->
        <transition name="el-zoom-in-top">
            <el-card v-show="moreVisible" class="more">
                <el-form label-width="80px">
                    <el-form-item class="input" label="Headers:" size="mini">
                        <el-input v-model="headers" size="mini"></el-input>
                    </el-form-item>
                    <el-form-item class="input" label="Cookies:" size="mini">
                        <el-input v-model="cookies" size="mini"></el-input>
                    </el-form-item>
                </el-form>
            </el-card>
        </transition>

        <!--textarea-->
        <el-card class="textarea">
            <el-form label-width="80px">
                <el-form-item class="input" label="Params:">
                    <dynamic-k-v-input v-model="params"></dynamic-k-v-input>
                </el-form-item>
                <div class="operation">
                    <el-switch class="switch" v-model="textareaVisible"></el-switch>
                    <el-button type="text" @click="params=[]">清空参数</el-button>
                    <el-button type="text" @click="result={}">清空结果</el-button>
                    <el-button type="text" @click="copyResultClick">复制结果</el-button>
                </div>
                <el-form-item class="input" label="Result:">
                    <el-input v-if="textareaVisible" type="textarea" class="textarea-input"
                              :value="JSON.stringify(result,'',2)" autosize></el-input>
                    <vue-json-editor v-else v-model="result" :show-btns="false"></vue-json-editor>
                </el-form-item>
            </el-form>
        </el-card>

        <!--dialog-->
        <template>
            <http-client-test-project-management-dialog
                    v-model="dialog.visible"
                    v-if="dialog.visible"
                    :type="dialog.type"
                    @save="loadOption"/>
        </template>

    </div>
</template>

<script type="text/ecmascript-6">
    import {R, Key} from '#/r';
    import {requestMethods} from './request-methods';
    import {clipboard} from 'electron';
    import axios from 'axios';

    import Background from "../../components/common/Background";
    import Operation from "../../components/common/Operation";
    import HttpClientTestProjectManagementDialog from "../../components/http-client-test/ProjectManagementDialog";
    import VueJsonEditor from "vue-json-editor";
    import DynamicKVInput from "../../components/http-client-test/DynamicKVInput";

    /**
     * @author 白雨浓
     * @date 2018/9/29 10:12
     *
     * Http测试（模拟浏览器环境）
     **/
    export default {
        name: 'HttpClientTest',
        components: {DynamicKVInput, VueJsonEditor, HttpClientTestProjectManagementDialog, Operation, Background},
        data() {
            return {
                requestMethods: requestMethods,
                dialog: {
                    visible: false,
                },
                moreVisible: false,
                textareaVisible: false,
                loading: false,
                option: {},
                activeOptionProject: '',
                method: 'POST',
                url: 'http://localhost:10010/login',
                headers: '',
                cookies: '',
                params: [{key: 'id', val: '1'}, {key: 'password', val: '1'}],
                result: undefined,
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.loadOption();
            })
        },
        methods: {
            loadOption() {
                const options = this.$storage.local.getItem(Key.local.HTTP_CLIENT_TEST_OPTION);
                const activeOptionProject = this.$storage.local.getItem(Key.local.HTTP_CLIENT_TEST_ACTIVE_PROJECT);

                if (options && activeOptionProject && options[activeOptionProject]) {
                    this.option = options[activeOptionProject];
                    this.activeOptionProject = activeOptionProject;
                }
            },
            settingClick() {
                this.dialog = {
                    visible: true,
                    type: R.dialog.EDIT
                }
            },
            goClick() {

                let config = {};

                if (this.params && this.params.length !== 0) {

                    const params = {};
                    for (const param of this.params) {
                        if (param.key) {
                            params[param.key] = param.val;
                        }
                    }

                    if ([requestMethods.GET, requestMethods.DELETE].includes(this.method)) {
                        config.params = params;
                    } else {
                        config.data = params;
                    }
                }

                this.loading = true;

                this.handleSaveUrl();

                axios({
                    method: this.method.toLowerCase(),
                    url: this.url,
                    ...config
                })
                    .then(res => {
                        this.result = res.data;
                        this.loading = false;
                    })
                    .catch(err => {
                        console.log(JSON.stringify(err));
                        this.result = err.response;
                        this.loading = false;
                    });
            },
            copyResultClick() {
                clipboard.writeText(JSON.stringify(this.result));
            },
            handleSaveUrl() {
                const key = `${this.method} : ${this.url}`;

                this.option.paths[key] = {
                    method: this.method,
                    url: this.url,
                    headers: this.headers,
                    cookies: this.cookies,
                    params: this.params
                };

                setTimeout(() => {
                    const options = this.$storage.local.getItem(Key.local.HTTP_CLIENT_TEST_OPTION);
                    const activeOptionProject = this.$storage.local.getItem(Key.local.HTTP_CLIENT_TEST_ACTIVE_PROJECT);

                    options[activeOptionProject] = this.option;
                    this.$storage.local.setItem(Key.local.HTTP_CLIENT_TEST_OPTION, options);
                }, 30);
            }
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .http-client-test {
    }

    .option-tag {
        margin-right 5px
    }

    .option-input {
        width 200px
        margin-right 10px
    }

    .setting-btn {
        color white
    }

    .console {
        display flex
        width 90%
        margin 20px auto

        .select {
            width 130px
            margin-right 5px
        }

        .input {

        }

        .go-btn {
            margin-left 20px
        }

        .input-btn {
            cursor pointer
        }
    }

    .more {
        width 90%
        margin 20px auto

        .input {
            margin 10px auto
        }
    }

    .textarea {
        width 90%
        margin 20px auto
    }

    .textarea-input {
        textarea {
            font-family 'Microsoft YaHei', serif !important
            color black !important
        }
    }

    .operation {
        display flex
        align-items center
        justify-content flex-end

        .switch {
            margin-right 10px
        }

    }


</style>
